package tool

import (
	"fmt"
	"github.com/gin-contrib/sessions"
	"github.com/gin-gonic/gin"
	"log"
)
import "github.com/gin-contrib/sessions/redis"

func InitSession(engine *gin.Engine) {
	config := GetConfig().Redis
	address := fmt.Sprintf("%s:%s", config.Host, config.Port)

	store, err := redis.NewStore(10, "tcp", address, "")
	if err != nil {
		log.Printf("init session: %v", err)
		return
	}
	engine.Use(sessions.Sessions("session", store))
}

func SetSession(ctx *gin.Context, key interface{}, value interface{}) error {
	session := sessions.Default(ctx)
	if session == nil {
		return nil
	}
	session.Set(key, value)
	return session.Save()
}

func GetSession(ctx *gin.Context, key interface{}) interface{} {
	session := sessions.Default(ctx)
	if session == nil {
		return nil
	}
	return session.Get(key)
}

